package com.ljj;


import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 19182
 * Date: 2025-11-19
 * Time: 9:23
 */
@RestController
@RequestMapping("/request2")
public class RequestController2 {
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request){
        Cookie[]  cookies = request.getCookies();
        if(cookies != null){
            for(Cookie cookie : cookies){
                System.out.println(cookie.getName() + "=" + cookie.getValue());
            }
        }
        return "获取cookie成功";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("name") String name){
        return "获取cookie成功 name:" + name;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request, String name){
        //获取Session
        HttpSession session = request.getSession();
        session.setAttribute("name", name);
        session.setAttribute("age", 18);
        session.setAttribute("userInfo", new Person("zhangsan", 1, 17));
        return "设置session成功";
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request){
        //获取Session
        //这里加上false是判断如果没有先创建Session对象，那么就返回null
        HttpSession session = request.getSession(false);
        if(session != null){
            System.out.println("name:" + session.getAttribute("name"));
            System.out.println("userInfo" + session.getAttribute("userInfo"));
        }
        return "获取Session成功"  + session.getAttribute("name");
    }
    @RequestMapping("/getSession2")
    public String getSession2(@SessionAttribute("name") String name){
        return "获取Session成功, name:" + name;
    }
    @RequestMapping("/getSession3")
    public String getSession3(HttpSession session){
        return "获取Session成功, name:" + session.getAttribute("name");
    }
    @RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request){
        String userAgent = request.getHeader("User-Agent");
        return "userAgent" + ":" +userAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent){
        return "userAgetn" + ":" + userAgent;
    }
}
